package com.shizhanzhe.gxb.home.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.gxb.R;
import com.shizhanzhe.gxb.base.UserBean;
import com.shizhanzhe.gxb.home.adapter.PDDRelatedAdapter;
import com.shizhanzhe.gxb.home.bean.PDDDetail;
import com.shizhanzhe.gxb.home.bean.PDDURL;
import com.shizhanzhe.gxb.url.Path;
import com.shizhanzhe.gxb.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.gxb.utils.Util;
import com.shizhanzhe.gxb.widget.ShareUrlPopwindow;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;


/**
 * Created by zz9527 on 2018/12/17.
 */
public class PDDDetailActivity extends Activity {
    private PDDDetail pddDetail;
    private PDDURL pddduo;
    private PDDURL pdddan;
    View statusBarView;
    private void initStatusBar() {
        if (statusBarView == null) {
            //利用反射机制修改状态栏背景
            int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
            statusBarView = getWindow().findViewById(identifier);
        }
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(R.drawable.shape_them);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdddetail);
        ImmersionBar.with(this)
                .statusBarView(R.id.bar_0_view)
                .init();
//        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                initStatusBar();
//                getWindow().getDecorView().removeOnLayoutChangeListener(this);
//            }
//        });
        findViewById(R.id.backarea).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        final ImageView img = (ImageView) findViewById(R.id.img);
        final TextView title = (TextView) findViewById(R.id.tv_title);
        final TextView qhprice = (TextView) findViewById(R.id.tv_quan_hou_price);
        final TextView nowprice = (TextView) findViewById(R.id.tv_price_on_line);
        final TextView sell = (TextView) findViewById(R.id.tv_sell_count);
        final TextView time = (TextView) findViewById(R.id.time);
        final TextView qprice = (TextView) findViewById(R.id.tv_quan_price);
        final TextView yongjin = (TextView) findViewById(R.id.yongjin);
        final TextView yongjin2 = (TextView) findViewById(R.id.yj);
        final TextView tv_share = (TextView) findViewById(R.id.tv_share);
        final LinearLayout buy = (LinearLayout) findViewById(R.id.buy);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final TextView level = (TextView) findViewById(R.id.level);
        final TextView uplevel = (TextView) findViewById(R.id.uplevel);
        RecyclerView recycler = (RecyclerView) findViewById(R.id.recycler);
        final LinearLayout upvip = (LinearLayout) findViewById(R.id.up_vip);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycler.setLayoutManager(manager);
        final PDDRelatedAdapter mRelatedAdapter = new PDDRelatedAdapter(this);
        recycler.setAdapter(mRelatedAdapter);
        OkHttpDownloadJsonUtil.downloadJson(this, Path.PDDDETAIL(getIntent().getLongExtra("goods_id",0)+""), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                try {
                    Gson gson = new Gson();
                    pddDetail = gson.fromJson(json, PDDDetail.class);
                    Glide.with(PDDDetailActivity.this).load(pddDetail.getData().getGoods_gallery_urls().get(0)).apply(new RequestOptions().error(R.mipmap.logo)).into(img);
                    title.setText(pddDetail.getData().getGoods_name());
                    double price = pddDetail.getData().getMin_group_price() / 100;
                    double price2 = ((double) pddDetail.getData().getMin_group_price() - (double) pddDetail.getData().getCoupon_discount()) / 100;
                    String yj1 = Util.Sub(price2 * ((double) pddDetail.getData().getPromotion_rate() / 1000) * UserBean.vipdivide + "");
                    String yj2 = Util.Sub(price2 * ((double) pddDetail.getData().getPromotion_rate() / 1000) * UserBean.divide + "");
                    String yj="";
                    if (UserBean.level==1) {
                        yj=yj1;
                        upvip.setVisibility(View.GONE);
                    }else {
                        yj=yj2;
                    }
                    level.setText("现在升级成为运营总监立即赚"+yj1+"元");
                    qhprice.setText(" " + price2 + "元");
                    nowprice.setText("原价:" + price + "元");
                    sell.setText("月销量:" + pddDetail.getData().getSold_quantity());
                    yongjin.setText("¥ " + yj);
                    yongjin2.setText("预计赚¥" + yj);
                    tv_share.setText("¥ " + yj);
                    if (pddDetail.getData().getCoupon_discount() != 0) {
                        qprice.setText(pddDetail.getData().getCoupon_discount() / 100 + "元优惠券");
                        time.setText("使用期限:" + getDateTimeFromMillisecond(pddDetail.getData().getCoupon_start_time()) + "-" + getDateTimeFromMillisecond(pddDetail.getData().getCoupon_end_time()));
                    } else {
                        buy.setVisibility(View.GONE);
                        nowprice.setText("");
                        tv.setText("优惠价:");
                    }


                    List<PDDDetail.ListBean> list = pddDetail.getList();
                    mRelatedAdapter.updateData(list);
                    mRelatedAdapter.setListener(new PDDRelatedAdapter.PDDSourceListener() {
                        @Override
                        public void click(PDDDetail.ListBean item) {
                            startActivity(new Intent(PDDDetailActivity.this, PDDDetailActivity.class).putExtra("goods_id", Long.parseLong(item.getGoods_id())));
                        }
                    });
                } catch (Exception e) {
                    Log.d("____",e.toString());
                    setResult(120);
                    Toast.makeText(PDDDetailActivity.this, "商品已下架", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        });


        OkHttpDownloadJsonUtil.downloadJson(this, Path.PDDURL(UserBean.uid, getIntent().getLongExtra("goods_id",0)+""), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
            @Override
            public void onsendJson(String json) {
                Gson gson = new Gson();
                try {
                    pdddan = gson.fromJson(json, PDDURL.class);
                    findViewById(R.id.buy).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(pdddan.getData().getMobile_short_url());
                            intent.setData(content_url);
                            startActivity(intent);
                        }
                    });
                    findViewById(R.id.buybar).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(pdddan.getData().getMobile_short_url());
                            intent.setData(content_url);
                            startActivity(intent);
                        }
                    });

                } catch (Exception e){
                    Log.d("____",e.toString());
                    Log.d("_____",json);
                    Toast.makeText(PDDDetailActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
        findViewById(R.id.share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final ShareUrlPopwindow wxPopupWindow = new ShareUrlPopwindow(PDDDetailActivity.this);
                wxPopupWindow.setWxListener(new ShareUrlPopwindow.ShareWxListener() {
                    @Override
                    public void shareDuo() {
                        wxPopupWindow.dismiss();
                        Wechat.ShareParams sp = new Wechat.ShareParams();
                        sp.setTitle(pddDetail.getData().getGoods_name());
                        sp.setText(pddDetail.getData().getGoods_desc());
                        sp.setUrl(pddduo.getData().getWe_app_web_view_short_url());
                        sp.setImageUrl(pddDetail.getData().getGoods_image_url());
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                        weChat.share(sp);
                    }

                    @Override
                    public void shareDan() {
                        Wechat.ShareParams sp = new Wechat.ShareParams();
                        sp.setTitle(pddDetail.getData().getGoods_name());
                        sp.setText(pddDetail.getData().getGoods_desc());
                        sp.setUrl(pdddan.getData().getWe_app_web_view_short_url());
                        sp.setImageUrl(pddDetail.getData().getGoods_image_url());
                        sp.setShareType(Platform.SHARE_WEBPAGE);
                        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
                        weChat.share(sp);
                    }
                });
                OkHttpDownloadJsonUtil.downloadJson(PDDDetailActivity.this, Path.PDDURL2(UserBean.uid, getIntent().getLongExtra("goods_id",0)+""), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        Gson gson = new Gson();
                        try {
                            pddduo = gson.fromJson(json, PDDURL.class);
                            wxPopupWindow.showDown(sell);
                        } catch (Exception e){
                            Log.d("____",e.toString());
                            Log.d("___",json);
                            Toast.makeText(PDDDetailActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });


        upvip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(PDDDetailActivity.this,VipActivity.class));
            }
        });
    }

    /**
     * 将毫秒转化成固定格式的时间
     * 时间格式: yyyy-MM-dd HH:mm:ss
     *
     * @param millisecond
     * @return
     */
    public static String getDateTimeFromMillisecond(long millisecond) {
        System.setProperty("user.timezone", "Asia/Shanghai");
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(tz);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(millisecond * 1000);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
